var pump = require('pump')
var tar = require('tar-stream')
var util = require('util')
var ReadableStream = require('readable-stream').Readable



function ObjectsStreams(options) {
    if (!(this instanceof ObjectsStreams)) {
      return new ObjectsStreams(options);
    }
    const opts = Object.assign(options || {}, { objectMode: true })
    ReadableStream.call(this, opts);
}

util.inherits(ObjectsStreams, ReadableStream);

ObjectsStreams.prototype._read = function() { }

function TarStreamToObjects  (inputStream, callback)  {
  var outputStream = new ObjectsStreams()
  var extractStream = tar.extract()

  extractStream.on('entry', function (header, stream, next) {
      stream.on('end', next)

      if (header.type !== 'directory') {
        outputStream.push({
          path: header.name,
          content: stream
        })
      } else {
        outputStream.push({
          path: header.name
        })
        stream.resume()
      }
    }).on('finish', function () {  outputStream.push(null) } )

  pump(inputStream, extractStream)
  callback(null, outputStream)
}

exports.tarStreamToObjects = function (inputStream) {
  return function (callback) {
    return function () {
      TarStreamToObjects(inputStream,function (a,b) {
         callback(b)();
      });
    }
  }
} 